﻿using Microsoft.Extensions.Caching.Memory;

namespace Ocelot.Admin.Api.Application
{
    public class DictionaryCacheService : IDictionaryCacheService, ITransient
    {
        public readonly SqlSugarScopeProvider _sqlserverDB;
        private readonly IMemoryCache _memoryCache;
        public DictionaryCacheService(ISqlSugarClient db, IMemoryCache memoryCache)
        {
            _sqlserverDB = db.AsTenant().GetConnectionScope(DatabaseConfigIdConst.OcelotSettings);
            _memoryCache = memoryCache;
        }

        public async Task<AllSelectResponse> GetAllSelectAsync()
        {
            var res = new AllSelectResponse();
            var selectKey = new string[] {
                CacheKeyConst.ConsulSettingKey,
                CacheKeyConst.ConsulDC,
            };
            var dictionaries = await _memoryCache.GetOrCreateAsync(CacheKeyConst.AllSelect, async entry =>
            {
                return await _sqlserverDB.Queryable<Dictionary>().With(SqlWith.NoLock)
                .Includes(o => o.DictionaryItems)
                .Where(o => selectKey.Contains(o.DictionaryType))
                .ToListAsync();
            });
            foreach (var dictionary in dictionaries)
            {
                switch (dictionary.DictionaryType)
                {
                    case CacheKeyConst.ConsulSettingKey:
                        res.ConsulSettingKey = dictionary.DictionaryItems.Select(o => new BaseSelectDto<string>()
                        {
                            Label = o.Key,
                            Value = o.Value
                        }).ToList();
                        ; break;
                    case CacheKeyConst.ConsulDC:
                        res.ConsulDC = dictionary.DictionaryItems.Select(o => new BaseSelectDto<string>()
                        {
                            Label = o.Key,
                            Value = o.Value
                        }).ToList();
                        ; break;

                    default:
                        res.ConsulDC = dictionary.DictionaryItems.Select(o => new BaseSelectDto<string>()
                        {
                            Label = o.Key,
                            Value = o.Value
                        }).ToList();
                        ; break;
                }
            }
            return res;
        }
    }
}
